# -*- coding: utf-8 -*-
"""
author:码同学 极光
date:2024/10/26
desc: 
sample: 
"""
import csv
import hashlib

import os
from email.mime.text import MIMEText


def get_flie_path(file_name):
    base_path = os.path.dirname(__file__)  # util相关路径
    file_path = os.path.join(base_path, 'data', file_name)
    return file_path



# [[],[]]
def getcsvlist(file_name, header=True):
    idlist = []
    with open(get_flie_path(file_name), encoding='utf-8') as f:
        csv_reader = csv.reader(f)
        if header == True:
            next(csv_reader)
        for line in csv_reader:
            idlist.append(line)
    return idlist


# [{},{}]
def getcsvlist_dict(file_name):
    list = []
    with open(get_flie_path(file_name), encoding="utf-8") as f:
        csv_reader = csv.DictReader(f)
        for line in csv_reader:
            list.append(line)
    return list


from openpyxl import load_workbook


def get_excel_to_list(filename, header=True):
    # 加载工作簿
    wb = load_workbook(get_flie_path(filename))
    # 获取默认的工作表
    ws = wb.active
    # 创建一个空列表来保存所有的行数据
    data = []
    if header == True:
        min_row = 2
    else:
        min_row = 1
    # 遍历工作表中的每一行
    for row in ws.iter_rows(min_row=min_row, values_only=True):
        # 将每行转换为列表并添加到总的列表中
        data.append(list(row))
    return data


def get_excel_to_list_dict(filename):
    # 加载工作簿
    wb = load_workbook(get_flie_path(filename))

    # 获取默认的工作表
    ws = wb.active
    # 获取第一行的数据
    # headers= []
    # first_row = ws[1]
    # # 遍历第一行的每个单元格并打印值
    # for cell in first_row:
    #     headers.append(cell.value)
    # 获取第一行作为列标题
    headers = [cell.value for cell in next(ws.iter_rows())]
    #headers = [cell for cell in next(ws.iter_rows(values_only=True))]
    # 创建一个空列表来保存所有的行数据
    data = []
    # 从第二行开始遍历工作表中的每一行
    for row in ws.iter_rows(min_row=2, values_only=True):
        # 将每行转换为字典并添加到总的列表中
        row_dict = dict(zip(headers, row))
        data.append(row_dict)
    return data


import os
import zipfile
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders


def zip_folder(folder_path, output_path):
    """将指定文件夹压缩成 ZIP 文件"""
    with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                zipf.write(os.path.join(root, file),
                           os.path.relpath(os.path.join(root, file),
                                           start=folder_path))





import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders


def send_email_with_attachment_163(sender_email, sender_password, receiver_email, subject, body, attachment_path=None):
    # 创建 MIMEMultipart 对象
    msg = MIMEMultipart()

    # 设置邮件头部信息
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject

    # 添加邮件正文
    msg.attach(MIMEText(body, 'plain'))

    # 读取附件文件
    if attachment_path is not  None:
      with open(attachment_path, "rb") as attachment:
        # 设置 MIMEBase 对象
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(attachment.read())
        encoders.encode_base64(part)

        # 添加附件头信息
        part.add_header(
            'Content-Disposition',
            f'attachment; filename= {attachment_path.split("/")[-1]}'
        )
        # 将附件附加到邮件中
        msg.attach(part)


    # 连接到 SMTP 服务器并发送邮件
    try:
        server = smtplib.SMTP('smtp.163.com', 25)  # 使用 Gmail 的 SMTP 服务器
        server.starttls()  # 启用 TLS 加密
        server.login(sender_email, sender_password)  # 登录 SMTP 服务器
        text = msg.as_string()
        server.sendmail(sender_email, receiver_email, text)
        server.quit()
        print("邮件发送成功！")
    except Exception as e:
        print(f"邮件发送失败: {e}")

def getMd5(data):
  # 创建一个md5哈希对象
  md5_hash = hashlib.md5()

  # 更新哈希对象，传入需要哈希的数据
   # 注意：如果你的数据不是字节类型，需要先将其编码为字节
  md5_hash.update(data.encode('utf-8'))

    # 获取哈希值的十六进制表示
  digest = md5_hash.hexdigest()
  return digest


if __name__ == '__main__':
    print(os.getcwd())  # 当前文件路径
    file_path = os.path.join(os.getcwd(), 'data','id.csv')
    print(file_path)
    # print(getcsvlist('id.csv'))
    # print(getcsvlist('id.txt', header=False))
    # print(getcsvlist_dict('case.csv'))
    # 使用函数读取 Excel 文件
    # print(get_excel_to_list('case.xlsx'))
    # filename = 'case.xlsx'  # 更改为你实际的文件名或路径
    # data_list = get_excel_to_list_dict(filename)
    # print(data_list)
    # 要压缩的文件夹路径
    # 示例调用
    sender_email = "testfan2@163.com"
    sender_password = "MSQOTDVQPMKSRZZS"
    receiver_email = "279313259@qq.com"
    subject = "测试邮件"
    body = "这是一封带有附件的测试邮件。"
    attachment_path = r"D:\PycharmProjects\flaskProject\pythonProject_0921_test\mypytest\allure-report_20241101_223428.zip"

    send_email_with_attachment_163(sender_email, sender_password, receiver_email, subject, body, attachment_path)